package com.woniuxy.opencv.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.opencv.pojo.ParkingRecord;
import com.woniuxy.opencv.service.ParkingRecordService;
import com.woniuxy.opencv.mapper.ParkingRecordMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 停车记录服务实现类
 */
@Service
public class ParkingRecordServiceImpl extends ServiceImpl<ParkingRecordMapper, ParkingRecord>
    implements ParkingRecordService {

    @Override
    @Transactional
    public ParkingRecord recordVehicleEntry(String plateNumber, Integer parkingId, Integer vehicleType) {
        // 检查车辆是否已经在停车场内
        ParkingRecord existingRecord = getVehicleCurrentParkingStatus(plateNumber);
        if (existingRecord != null) {
            throw new RuntimeException("该车辆已在停车场内，车牌号：" + plateNumber);
        }

        // 创建新的停车记录
        ParkingRecord record = new ParkingRecord();
        record.setPlateNumber(plateNumber);
        record.setParkingId(parkingId);
        record.setVehicleType(vehicleType);
        record.setStartTime(new Date());
        record.setStatus(0); // 0表示未出场

        // 保存记录
        save(record);
        return record;
    }

    @Override
    @Transactional
    public ParkingRecord recordVehicleExit(String plateNumber, Integer parkingId) {
        // 查找车辆的停车记录
        ParkingRecord record = getVehicleCurrentParkingStatus(plateNumber);
        if (record == null) {
            throw new RuntimeException("未找到该车辆的停车记录，车牌号：" + plateNumber);
        }

        // 验证停车场ID
        if (!record.getParkingId().equals(parkingId)) {
            throw new RuntimeException("车辆不在该停车场内，车牌号：" + plateNumber);
        }

        // 更新记录
        record.setEndTime(new Date());
        record.setStatus(1); // 1表示已出场
        updateById(record);

        return record;
    }

    @Override
    public ParkingRecord getVehicleCurrentParkingStatus(String plateNumber) {
        LambdaQueryWrapper<ParkingRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkingRecord::getPlateNumber, plateNumber)
                   .eq(ParkingRecord::getStatus, 0) // 未出场的记录
                   .orderByDesc(ParkingRecord::getStartTime)
                   .last("LIMIT 1");
        
        return getOne(queryWrapper);
    }

    @Override
    public List<ParkingRecord> getAllParkingRecords() {
        return this.list();
    }

    @Override
    public ParkingRecord getByOrderId(Long orderId) {
        LambdaQueryWrapper<ParkingRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkingRecord::getOrderId, orderId);
        return getOne(queryWrapper);
    }
}




